import logging

from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *

logger = logging.getLogger(__name__)

def dump_error(out_path, error_msg):
    temp_dir = tempfile.mkdtemp()
    try:
        os.mkdir(os.path.join(temp_dir, 'output'))
        with open(os.path.join(temp_dir, 'output', 'error_msg.txt'), 'w') as f:
            f.write(error_msg)
            f.close()
        archive = zipfile.ZipFile(os.path.join(temp_dir, 'archive.zip'), 'w')
        try:
            archive.write(os.path.join(temp_dir, 'output', 'error_msg.txt'), '/error_msg.txt')
        finally:
            archive.close()
            shutil.move(os.path.join(temp_dir, 'archive.zip'), output_path)
    finally:
        shutil.rmtree(temp_dir)

class CrashHandlerWindow(QWidget):
    exiting = pyqtSignal()

    def __init__(self, error_msg, title='Crash Handler - File Browser'):
        super().__init__()
        self.exiting.connect(self.destroy)
        layout = QVBoxLayout()
        self.setWindowTitle(title)
        self.message_label = QLabel('Oops! Something went wrong:')
        layout.addWidget(self.message_label)
        self.error_msg_display = QTextEdit()
        self.error_msg_display.setText(error_msg)
        self.error_msg_display.setReadOnly(True)
        layout.addWidget(self.error_msg_display)
        options_layout = QHBoxLayout()
        self.save_error_button = QPushButton('Save Error Information')
        self.save_error_button.clicked.connect(self.save_error)
        options_layout.addWidget(self.save_error_button)
        self.close_button = QPushButton('Exit')
        self.close_button.clicked.connect(lambda: self.exiting.emit())
        options_layout.addWidget(self.close_button)
        layout.addLayout(options_layout)
        self.setLayout(layout)

    def save_error(self):
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        file_path, _ = QFileDialog.getSaveFileName(self, "Open file", "", "Archived Error Information (*.error);;Zip Archive (*.zip);;All Files (*)", options=options)
        if file_path:
            dump_error(file_path, error_msg)

    def closeEvent(self, event):
        self.exiting.emit()
        QWidget.closeEvent(self, event)
